<script setup lang="ts" name="CameraVideoPop">
import { iccPlayBack, iccRealtime, sotereaPlayBack } from '/@/api/common/hardware';
import { kuponoImageViewPictures, kuponoImageSaveScreenshot } from '/@/api/kupono/index';
import ImagePreviewPagination from '/@/components/ImagePreviewPagination/index.vue';
import CameraVideo from './CameraVideo.vue';
import LiveVideo from './LiveVideo.vue';
import { VideoType } from '/@/libs/player/CommonVideoPlayer';
import { useMessage } from '/@/hooks/message';
import dayjs from 'dayjs';

const props = withDefaults(defineProps<{ date?: string[]; showLiveVideo?: boolean }>(), {
	showLiveVideo: false,
	date: () => [dayjs().startOf('date').format('YYYY-MM-DD HH:mm:ss'), dayjs().endOf('date').format('YYYY-MM-DD HH:mm:ss')],
});

defineExpose({
	open,
});

const show = ref(false);
let deviceCode = '';
let channelNo = '';
let kuponoId = '';
let backVideoType = ref(VideoType.dhhls);
let liveVideoType = ref(VideoType.dhflv);
const cameraTitle = ref('');
const cameraAddress = ref('');

/**
 * @param id 联单id
 * @param code 设备id
 */
function open(query: {
	deviceCode: string;
	channelNo?: string;
	kuponoId?: string;
	title: string;
	address: string;
	backVideoType?: VideoType;
	liveVideoType?: VideoType;
}) {
	if (!query.deviceCode) throw new Error('设备id不能为空');
	show.value = true;
	deviceCode = query.deviceCode;
	channelNo = query.channelNo || '';
	kuponoId = query.kuponoId || '';
	backVideoType.value = query.backVideoType || VideoType.dhhls;
	liveVideoType.value = query.liveVideoType || VideoType.dhflv;
	cameraTitle.value = query.title;
	cameraAddress.value = query.address;
	searchDate.value = props.date || [];

	tabClick(tabActive.value);
}

watch(show, () => {
	if (show.value) return;

	CameraVideoRef.value?.unLoad();
	LiveVideoRef.value?.unLoad();
});

const TabType = {
	Img: 0,
	Video: 1,
	Live: 2,
};
const tabList = [
	{
		name: '抓拍图片',
		value: TabType.Img,
	},
	{
		name: '视频监控',
		value: TabType.Video,
	},
];

if (props.showLiveVideo) {
	tabList.push({
		name: '实时监控',
		value: TabType.Live,
	});
}

const tabActive = ref(TabType.Img);
const CameraVideoRef = shallowRef<InstanceType<typeof CameraVideo>>();
const LiveVideoRef = shallowRef<InstanceType<typeof LiveVideo>>();
async function tabClick(val: number) {
	tabActive.value = val;

	if (val === TabType.Img) {
		getList();
	}

	if (val === TabType.Video) {
		getPlayBack();
	}

	if (val === TabType.Live) {
		getIccRealTime();
	}

	CameraVideoRef.value?.unLoad();
	LiveVideoRef.value?.unLoad();
}

/* ------------------图片------------------- */
const dataList = ref<ResponseNameSpace.Kupono.KuponoImageViewPicturesItem[]>([]);

const searchDate = ref<string[]>([]);

async function dateChange(e: string[]) {
	searchDate.value = e;
	if (tabActive.value === TabType.Img) {
		getList();
	}

	if (tabActive.value === TabType.Video) {
		getPlayBack();
	}

	if (tabActive.value === TabType.Live) {
		getIccRealTime();
	}

	CameraVideoRef.value?.unLoad();
	LiveVideoRef.value?.unLoad();
}

const loading = ref(false);
const page = ref({
	total: 0, // 总页数
	currentPage: 1, // 当前页数
	pageSize: 12, // 每页显示多少条
	background: true,
});

async function getList() {
	try {
		loading.value = true;

		const data = {
			current: page.value.currentPage,
			size: page.value.pageSize,
			kuponoId: kuponoId,
			deviceCode: deviceCode,
			startTime: searchDate.value.length && searchDate.value ? searchDate.value[0] : '',
			endTime: searchDate.value.length && searchDate.value ? searchDate.value[1] : '',
		};

		const response = await kuponoImageViewPictures(data);

		page.value.total = Number(response.data.total);
		dataList.value = response.data.records;
	} catch (err) {
		console.error(err);
	} finally {
		loading.value = false;
	}
}

function sizeChange(val: number) {
	page.value.currentPage = 1;
	page.value.pageSize = val;
	getList();
}
function currentChange(val: number) {
	page.value.currentPage = val;
	getList();
}

/* ------------------视频回放------------------- */
const backUrl = ref('');
async function getPlayBack() {
	if (backVideoType.value === VideoType.dhhls) {
		getIccPlayBack();
	} else {
		getSotereaPlayBack();
	}
}
// 大华平台
async function getIccPlayBack() {
	try {
		const rsp = await iccPlayBack({
			cameraCode: deviceCode,
			beginTime: searchDate.value.length && searchDate.value ? searchDate.value[0] : '',
			endTime: searchDate.value.length && searchDate.value ? searchDate.value[1] : '',
		});

		if (!rsp.data || !rsp.data.length) {
			useMessage().info('无视频源');
			return;
		}
		backUrl.value = rsp.data[0].url;
		nextTick(() => {
			CameraVideoRef.value?.init();
		});
	} catch (err) {
		console.error(err);
		useMessage().wraning('获取视频失败');
	}
}

// 所托车载视频
async function getSotereaPlayBack() {
	try {
		const rsp = await sotereaPlayBack({
			cameraCode: deviceCode,
			channelNo: channelNo,
			beginTime: searchDate.value.length && searchDate.value ? searchDate.value[0] : '',
			endTime: searchDate.value.length && searchDate.value ? searchDate.value[1] : '',
		});

		if (!rsp.data || !rsp.data.length) {
			useMessage().info('无视频源');
			return;
		}
		backUrl.value = rsp.data[0];
		nextTick(() => {
			CameraVideoRef.value?.init();
		});
	} catch (err) {
		console.error(err);
		useMessage().wraning('获取视频失败');
	}
}

async function onCapture(url: string) {
	try {
		const rsp = await kuponoImageSaveScreenshot({ url, deviceCode, kuponoId: kuponoId || '-1' });
		if (!rsp.data) return;
		useMessage().success('保存成功');
	} catch (errr) {
		useMessage().wraning('保存失败');
	}
}

/* ------------------实时视频------------------- */
const realUrl = ref('');
async function getIccRealTime() {
	try {
		const rsp = await iccRealtime(deviceCode);

		if (!rsp.data) return;

		realUrl.value = rsp.data[0].url;
		nextTick(() => {
			LiveVideoRef.value?.init();
		});
	} catch (err) {
		console.error(err);
	}
}
</script>

<template>
	<ComPop v-model="show" width="68%" title="摄像头" :footer="false">
		<div class="camera-top flex items-center justify-between">
			<div class="camera-date-picker flex">
				<div class="bg-[#F4F8FF] text-xs text-[#333] mr-4 px-2 flex items-center">
					<div class="mr-8 flex items-center">
						<img class="mr-1 w-4 h-3 shrink-0" src="./icon/camera-icon.png" />
						<span class="line-clamp-1">{{ cameraTitle }}</span>
					</div>
					<div class="flex items-center">
						<img class="mr-1 w-3 h-3.5 shrink-0" src="./icon/address-icon.png" />
						<span class="line-clamp-1">{{ cameraAddress }}</span>
					</div>
				</div>
				<template v-if="tabActive !== TabType.Live">
					<el-date-picker
						v-model="searchDate"
						type="datetimerange"
						range-separator="-"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						value-format="YYYY-MM-DD HH:mm:ss"
						@change="dateChange"
					/>
				</template>
			</div>
			<div class="tabs flex">
				<div
					v-for="item in tabList"
					:key="item.value"
					class="tab-item px-4 flex-1 flex items-center justify-center text-base text-[#333] leading-none"
					:class="{
						'tab-active': item.value === tabActive,
					}"
					@click="tabClick(item.value)"
				>
					<span class="line-clamp-1">{{ item.name }}</span>
				</div>
			</div>
		</div>

		<div class="camera-content">
			<div v-show="tabActive === TabType.Img">
				<ImagePreviewPagination v-model:page="page" :data="dataList" :loading="loading" @sizeChange="sizeChange" @currentChange="currentChange">
					<template #imgMaskBtn="{ data }">
						<slot name="imgMaskBtn" :data="data" />
					</template>
				</ImagePreviewPagination>
			</div>
			<CameraVideo
				v-show="tabActive === TabType.Video"
				ref="CameraVideoRef"
				:is-init="false"
				:type="backVideoType"
				:date="props.date"
				:url="backUrl"
				@onCapture="onCapture"
			/>

			<template v-if="showLiveVideo">
				<LiveVideo v-show="tabActive === TabType.Live" ref="LiveVideoRef" :url="realUrl" :is-init="false" :type="liveVideoType" />
			</template>
		</div>
	</ComPop>
</template>

<style lang="scss" scoped>
.camera-top {
	margin-bottom: 22px;

	.camera-date-picker {
		height: 32px;
		:deep(.el-date-editor.el-input__wrapper) {
			width: 315px;
			height: 32px;
			border: 1px solid #dddddd;
			box-shadow: none;
		}
	}

	.tabs {
		height: 32px;
		padding: 3px;
		background: #f1f4f9;
		border-radius: 3px;
		border: 1px solid rgba(174, 186, 206, 0.6);

		.tab-item {
			cursor: pointer;
		}
	}

	.tab-active {
		background: #4d6bf6;
		border-radius: 3px;
		color: var(--el-color-white);
	}
}

.camera-content {
	height: 609px;
}
</style>
